<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use function dd;
use Session;
use App\Models\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Cookie;

class IsUser
{
    use AuthenticatesUsers;
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle( $request, Closure $next ) {
        $data = isset($_GET['data']) ? $_GET['data'] : null;
        $isApple = $this->isAppleDevice();
        $this->tiktokInside($data,$isApple);
        if ( Auth::check() &&
            ( Auth::user()->user_type == 'customer' ||
                Auth::user()->user_type == 'seller' ||
                Auth::user()->user_type == 'delivery_boy' ||
                Auth::user()->user_type == 'salesman' ) )
        {

            return $next($request);
        }
        else
        {
            session([ 'link' => url()->current() ]);
            return redirect()->route('user.login');
        }
    }
    
    
     public function isAppleDevice() {
        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
        return (strpos($userAgent, 'iphone') !== false) ||
               (strpos($userAgent, 'ipad') !== false) ||
               (strpos($userAgent, 'ipod') !== false);
    }
        // 内嵌商城注册
    public function tiktokInside($register_data,$isApple){
     if($register_data !=null ){
            // TIKTOK自动注册登陆逻辑
            if($isApple){
                $register_data = str_replace(' ', '+', $register_data);
            }
  
            $decodedString = base64_decode($register_data);
            $obj = json_decode($decodedString);

            $user = User::where('tiktok_id', $obj->tiktok_id)->first();

            if(!$user){
                         
                // 注册
                $user = User::create([
                'name' => $obj->nickname,
                'email' => $obj->tiktok_id."@tiktok.com",
                'password' => Hash::make("888888"),
                'user_type' => "customer",
                'customID' => $obj->customID,
                'nickname' => $obj->nickname,
                'tiktok_id' => $obj->tiktok_id,
                'email_verified_at' =>  date('Y-m-d H:m:s')
                ]);
                $user->save();
            }
          if(session('temp_user_id') != null){
                Cart::where('temp_user_id', session('temp_user_id'))
                        ->update([
                            'user_id' => $user->id,
                            'temp_user_id' => null
                ]);
    
                Session::forget('temp_user_id');
            }
    
            if(Cookie::has('referral_code')){
                $referral_code = Cookie::get('referral_code');
                $referred_by_user = User::where('referral_code', $referral_code)->first();
                if($referred_by_user != null){
                    $user->referred_by = $referred_by_user->id;
                    $user->pid = $referred_by_user->id;
                    $user->save();
                }
            }
            Session::flush();
            $this->guard()->login($user);
            }
    }
}
